package com.py.chat.server;

import java.net.InetSocketAddress;

import com.google.protobuf.MessageLite;
import com.py.chat.bean.Gloable;
import com.py.chat.bean.User;
import com.py.chat.proto.ProtoMapper;
import com.py.chat.utils.PropertiesUtil;


import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;

import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

//服务端
public class ChatServer {

	static final int PORT = Integer.parseInt(PropertiesUtil.getValue("port"));

	public static void main(String[] args) throws Exception {
		ProtoMapper.init();
		Gloable.init();
		EventLoopGroup bossGroup = new NioEventLoopGroup(1);
		EventLoopGroup workerGroup = new NioEventLoopGroup();
		try {
			ServerBootstrap b = new ServerBootstrap();
			b.group(bossGroup, workerGroup)
			.channel(NioServerSocketChannel.class)
					.handler(new LoggingHandler(LogLevel.INFO))
					.childHandler(new ServerInitializer());
			b.bind(PORT).sync().channel().closeFuture().sync();
		} finally {
			bossGroup.shutdownGracefully();
			workerGroup.shutdownGracefully();
		}
	}
	//全局广播
	public static void broadcast(MessageLite msg) {
		for (User user : Gloable.sessionMap.values()) {
			user.session.channel.writeAndFlush(msg);
		}
	}
	//全局广播除了某个用户
	public static void broadcast(MessageLite msg,User user) {
		for (User userMap : Gloable.sessionMap.values()) {
			if(userMap.equals(user)){
				continue;
			}
			userMap.session.channel.writeAndFlush(msg);
		}
	}
}
